package com.newland.zxy.service;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;

/**
 * @author : zhangxuyuan
 * @Project: springsecurity
 * @Package com.newland.zxy.service
 * @date Date : 2021年02月08日 13:58
 */
@Service
public class LoginService {

    @Autowired
    private AuthenticationManager manager;

    //定义加密算法
    public static Key key= Keys.secretKeyFor(SignatureAlgorithm.HS256);


    public String login(String username,String password) throws Exception
    {
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(username,password);
        Authentication authenticate = manager.authenticate(authenticationToken);

        System.out.println(authenticate.getAuthorities());
        System.out.println(authenticate.getPrincipal());
        //获取用户名
        System.out.println(authenticate.getName());
        System.out.println(authenticate.getDetails());

        SecurityContextHolder.getContext().setAuthentication(authenticate);

        String jwtToken = Jwts.builder()
                .signWith(key)
                .claim("uid",authenticate.getName())
                .claim("authority",authenticate.getAuthorities())
                .setExpiration(new Date(System.currentTimeMillis()+10*60*1000))
                .compact();
        return jwtToken;
    }
}
